﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NHTrace
{
  public class SqlParameterParser
  {
    private string getParametersAsString(string statement)
    {
      int i = statement.IndexOf(";@p");
      if (i > 0)
        return statement.Substring(i + 1);
      else
        return string.Empty;
    }

    public Dictionary<string, string> GetParameters(string statement)
    {
      var result = new Dictionary<string, string>();

      var splittedParams = getParametersAsString(statement).Split(new char[] { ',' });

      var paramList = new List<string>();

      string aux = string.Empty;
      for (int i = 0; i < splittedParams.Length - 1; i++)
      {
        aux += splittedParams[i];

        if (!splittedParams[i + 1].Trim().StartsWith("@p"))
        {
          aux += ',';
          continue;
        }
        else
        {
          paramList.Add(aux.Trim());
          aux = string.Empty;
        }
      }

      aux += splittedParams[splittedParams.Length - 1];

      if (!string.IsNullOrEmpty(aux))
        paramList.Add(aux.Trim());

      foreach (var p in paramList)
      {
        var i = p.IndexOf(" = ");
        result.Add(p.Substring(0, i), p.Substring(i + " = ".Length));
      }

      return result;
    }
  }
}
